package rhc.discribute.node.connecter.impl.zookper.watchCallback;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event.EventType;

import rhc.discribute.BaseComponent;
import rhc.discribute.node.connecter.impl.ZKPathLockData;
import rhc.discribute.node.connecter.impl.ZookperExecute;
import rhc.discribute.node.connecter.impl.zookper.WatchCallback;
import rhc.discribute.node.exception.CallbackException;
import rhc.discribute.node.sendMessage.SendMessageCallback;
import rhc.discribute.node.sendMessage.SendMessageData;

public class ReceiveSuccessMessageWatchCallback extends BaseComponent implements WatchCallback {

	@Override
	public void executeCallback(WatchedEvent event, Object callbackData) throws CallbackException {
		SendMessageData dataMap = (SendMessageData) callbackData;

		ZookperExecute zkExecute = dataMap.getZkExecute();
		CountDownLatch latch = dataMap.getLatch();
		String messagePath = dataMap.getMessagePath();
		SendMessageCallback callback = dataMap.getCallback();
		ZKPathLockData zkLockData=dataMap.getZkLockData();

		try {
			if(null != latch && !latch.await(1, TimeUnit.MILLISECONDS)){
				if (event.getType() == EventType.NodeDataChanged) {
					latch.countDown();
					zkExecute.sendToHostMessageSuccess(messagePath,zkLockData, callback);
				} else {
					logger.error("监控消息发送成功回调收到异常事件，" + event);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(null != latch){
				latch.countDown();
			}
			dataMap.clear();
		}
	}

	@Override
	public boolean isSync() {
		return false;
	}

}
